<template>
    <div class="loginview">
        <form>
            <li>
                <label for="username">
                    用户名：<input type="text" id="username"
                        v-model="callcode"
                        placeholder="请输入您的用户名"
                        @blur="nameBlur" />
                </label>
                <div v-if="nameerror" >{{nameerror}}</div>
            </li>
            <li>
                <label for="userpassword">
                    密码：<input id="userpassword"
                        type="password"
                        v-model="password"
                        @blur="passwordBlur" />
                </label>
                <div v-if="passworderror">{{passworderror}}</div>
            </li>
            <button @click.prevent="login" :disabled="disabled">登录</button>
            <li class="other clearfloat">
                <span @click="changereg">新用户</span>
                <span>忘记密码</span>
            </li>
        </form>
    </div>
</template>

<script>
// 引入axios
import axios from 'axios';
import {
  ref,
  reactive,
  toRefs,
  computed,
} from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import SocketIO from 'socket.io-client';
import Store from '../../store/index';

export default {
  name: 'Loginform',
  setup() {
    // 初始化Store
    const store = useStore();
    const userinfor = reactive({
      callcode: '',
      password: '',
    });

    const router = useRouter();
    const nameerror = ref('');
    const passworderror = ref('');

    // 前端验证用户名是否通过
    const fname = ref(false);
    // 失去焦点时触发
    // 前端验证用户名
    function nameBlur() {
      if (userinfor.callcode.length === 0) {
        nameerror.value = '用户名不能为空';
        fname.value = false;
        return;
      }
      if (userinfor.callcode.length !== 11) {
        nameerror.value = '用户名为11位电话号码';
        fname.value = false;
        return;
      }
      const zz = /\W/;
      if (zz.test(userinfor.callcode)) {
        nameerror.value = '用户名只能使用数字和大小写字母及下划线';
        fname.value = false;
        return;
      }
      nameerror.value = '';
      fname.value = true;
    }

    // 前端验证密码是否通过
    const fpassword = ref(false);

    // 前端验证密码
    function passwordBlur() {
      if (userinfor.password.length === 0) {
        passworderror.value = '请输入密码';
        fpassword.value = false;
        return;
      }

      if (userinfor.password.length > 8) {
        passworderror.value = '密码最多有8位';
        fpassword.value = false;
        return;
      }

      const zz = /\W/;
      if (zz.test(userinfor.password)) {
        passworderror.value = '密码只能使用数字和大小写字母及下划线';
        fpassword.value = false;
        return;
      }

      passworderror.value = '';
      fpassword.value = true;
    }

    // 控制按钮的disabled
    const disabled = computed(() => {
      if (fname.value && fpassword.value) {
        return false;
      }
      return true;
    });

    function login() {
      axios.post('http://localhost:5001/api/login', {
        data: userinfor,
      }).then(
        // 请求获取成功回调
        (response) => {
          if (response.data.status === 200) {
            // 将token临时储存在本地浏览器
            window.sessionStorage.setItem('token', JSON.stringify(response.data.token));
            // 跳转到home页面,并传数据到route.query上
            router.replace({
              name: 'Me',
            });

            // 登录成功后建立socket连接
            const socket = SocketIO.connect('http://localhost:5001', {
              query: { calltonken: userinfor.callcode },
            });
            // 挂载socket通信实例在vuex中
            store.commit('MOUNTEDSOCKET', socket);

            // 接收消息
            store.state.basicinfor.socket.on('backinfor', (sendeecall, sendercall, msg) => {
              // 得到好友的昵称
              const sendname = Store.state.friendlist.friendslist.find((item) => {
                if (item.callcode === sendercall) {
                  return item;
                }
                return false;
              });
              // 生成消息对象   这可以改成构造函数，暂时不改
              const receive = {
                sender: sendercall,
                sendername: sendname.name,
                infortext: msg,
                sendee: sendeecall,
                yornsend: 'left',
                sendtime: Date.now(),
              };
              Store.commit('RECEIVEADDINFOR', receive);
            });

            // 接收好友申请的消息
            Store.state.basicinfor.socket.on('apply', (reqinfor) => {
              // 储存好友申请到vuex中
              Store.commit('ADDNEWFRIEND', reqinfor);
            });
          } else if (response.data.status === 1) {
            console.log(response.data);
          }
        },
        // 请求获取失败回调
        (error) => {
          console.log(error.message);
        },
      );
    }

    function changereg() {
      router.push('/registerview');
    }
    return {
      ...toRefs(userinfor),
      nameerror,
      passworderror,
      disabled,
      login,
      nameBlur,
      passwordBlur,
      changereg,
    };
  },
};
</script>

<style scoped>
    .loginview {
        font-size: 13px;
        text-align: right;
        padding: 10px;
        margin: 110px auto;
        width: 230px;
        background-color: #ffffff;
        border: 1px solid #34c8de;
        border-radius: 5px;
        box-shadow: 0 0 5px #34c8de;
    }
    li {
        margin: 25px auto;
    }
    input {
        width: 135px;
    }
    form li div{
        margin-top: 2px;
        margin-left: 73px;
        color: #FF0000;
        font-size: 12px;
        text-align: left;
    }
    button {
        width: 128px;
        height: 40px;
        margin: 5px 40px;
        background-color: #96fbcd;
        border-radius: 5px;
        border: none;
        font-weight: 700;
    }
    .other {
        margin: 15px auto 5px auto;
    }
    .other span:first-child {
        float: left;
    }
    .other span:last-child {
        float: riight;
    }
</style>
